import axios from 'axios';
import router from '../router';
import md5 from 'js-md5'
import JSONBIG from 'json-bigint';
import { ElMessage, } from "element-plus";

const formatParams = (data) => {
    let arr = [];
    for (let name in data) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    return arr.join("&");
}
/*设置baseURL*/
let baseURL = '/';
// process.env.NODE_ENV  用于判断当前运行环境，根据 npm run serve 或 npm run build 
if (process.env.NODE_ENV === 'production') {
    baseURL = '/';
} else {
}
axios.defaults.baseURL = baseURL;
axios.defaults.timeout = 45000; //超时时间
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

//处理数字长高度过长精度丢失问题
axios.defaults.transformResponse = [
    function (data) {
        try {
            const json = JSONBIG({
                storeAsString: true
            })
            return json.parse(data)
        } catch (err) {
            return data
        }
    }
]

//请求拦截
axios.interceptors.request.use(function (config) {
    var code = '' + (parseInt(Math.random() * 1000000) + 1000000);
    let nonce = code.substring(1, 7);
    let timestamp = Date.now();
    let appid = '2E9DA7B0F3CA7C4FABAE0C1EB944B156';
    let appSecret = '82F5FDE9C2C045C9A8015D7A01397F32';
    let token = sessionStorage.getItem("token");
    if (token) {
        let sign = md5(timestamp + nonce + appid + appSecret + token);
        config.headers.token = token;
        config.headers.nonce = nonce;
        config.headers.sign = sign;
        config.headers.appid = appid;
        config.headers.timestamp = timestamp;
    }
    //添加token验证机制
    if (process.env.NODE_ENV === "development") {
        if (config.url.startsWith("/javaApi")) {
            config.baseURL = "/javaApi"; // 取到环境变量：baseURL
        } else if (config.url.startsWith("/pythonApi")) {
            config.baseURL = "/pythonApi"; // 取到环境变量：baseURL
        } else {
            config.baseURL = "/bitApi"; // 取到环境变量：baseURL
        }
    }
    return config
})
//返回拦截
axios.interceptors.response.use(response => {
    const res = response.data;    //这是响应返回后的结果
    //在这里可以根据返回的状态码对存在响应错误的请求做拦截，提前做处理。
    // 如果自定义代码不是200，则判断为错误。
    if (res.code == 500) {
        // 重新登陆
        // ElMessage.error(res.msg);
        return res
    } else if (res.code == 300) {
        sessionStorage.clear();
        router.push("/login");
        // 重新登陆
        // ElMessage.error("登录超时");
        return res
    } else if (res.code == 400) {
        sessionStorage.clear();
        router.push("/login");
        // 重新登陆
        // ElMessage.error("非法请求");
        return res
    } else {
        return res
    }
}, error => {
    return Promise.reject(error);
})
export const httpService = (url, params, method, headers, loading = false) => {
    if (loading) {
        // var loadingInstance = ElLoading.service({
        // lock: true,
        // });
    }
    if (!headers) {
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }
    if (method === 'post') {
        return new Promise((resolve, reject) => {
            axios.post(url, params, {
                headers: headers
            }).then(data => {
                // if (loading) loadingInstance.close();
                resolve(data);
            }).catch(error => {
                reject(error);
                // // ElMessage.error('网络不给力');
                // if (loading) loadingInstance.close();
            });
        })
    }
    else {
        return new Promise((resolve, reject) => {
            axios.get(url + '?' + formatParams(params), headers).then(data => {
                resolve(data);
                // if (loading) loadingInstance.close();
            }).catch(error => {
                console.log(error)

                // ElMessage.error('网络不给力');
                // if (loading) loadingInstance.close();
                reject(error);
            });
        })
    }
}